package appx.craft.droid.uc;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import appx.craft.droid.R;
import appx.craft.droid.bean.FeedBean;
import appx.craft.droid.bean.JSONParams;
import appx.craft.droid.stricky.StickyListHeadersAdapter;
import appx.craft.droid.ui.onFeedCommentClickListner;
import appx.craft.droid.utils.Constance;
import appx.craft.droid.utils.Log;
import appx.craft.droid.utils.UtilityHelper;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class FeedAdapter extends BaseAdapter implements
		StickyListHeadersAdapter {

	private final static String TAG = FeedAdapter.class.getCanonicalName();

	private Context mContext;
	private LayoutInflater inflater;
	public static LinkedList<FeedBean> mFeedMessageList;
	private ImageLoader mAdapterLoader;
	private DisplayImageOptions mAdapterOptions;
	private Handler mLikeHandler = new Handler();
	private onFeedCommentClickListner mCommentCallback;
	private IFeedUploadListener muploadCallback;
	private NewShareImageTask mShareImageTask;
	
	public static boolean FlagIsClickable;
	
	ImageEncodingProcess mEncoding;
	
	IHeaderListener mHeaderUpdateCallback;
	
	/**
	 * 
	 * @param context Application Context 
	 * @param mImageLoader Image Loader for download images 
	 * @param mDisplayOption images properties 
	 */
	public FeedAdapter(Context context, final ImageLoader mImageLoader,
			final DisplayImageOptions mDisplayOption) {
		mContext = context;
		mCommentCallback = (onFeedCommentClickListner) mContext;
		muploadCallback = (IFeedUploadListener)mContext;
		mHeaderUpdateCallback = (IHeaderListener)mContext;
				
		inflater = LayoutInflater.from(context);
		mFeedMessageList = new LinkedList<FeedBean>();
		mAdapterLoader = mImageLoader;
		mAdapterOptions = mDisplayOption;
	}

	/**
	 * To clear Feed list and update list view 
	 */
	public void clearFeedList() {
		
		if (mFeedMessageList != null) {

			if (!mFeedMessageList.isEmpty()) {
				mFeedMessageList.clear();
			}

			// notified List view with new Feed List message
			notifyDataSetChanged();
		}
	}

	/**
	 * Add New Feed In Link List  mFeedMessageList
	 * @param mTempBean
	 */
	public synchronized void addNewFeedItem(final FeedBean mTempBean) {

		if (mFeedMessageList != null) {
			mFeedMessageList.add(mTempBean);
			notifyDataSetChanged();
		}
	}
	
	/**
	 * If need to add always first then refrence of Feed Bean class
	 * @param mTempBean
	 */
	public void addFirstFeed(final FeedBean mTempBean){
		
		if (mFeedMessageList != null) {
			mFeedMessageList.addFirst(mTempBean);
			notifyDataSetChanged();
		}
		
	}
	
	/**
	 * only update once user press latest feed 
	 * @param mUpdateBean
	 */
	public void updateFeed(final FeedBean mUpdateBean){
		if(FeedAdapter.mFeedMessageList != null && FeedAdapter.mFeedMessageList.size() > 0){
			
			for (int i = 0; i < FeedAdapter.mFeedMessageList.size(); i++) 
			{
				FeedBean mTempBean = FeedAdapter.mFeedMessageList.get(i);
				String strFeedType = mTempBean.getTypeID();
				if(strFeedType.equalsIgnoreCase(Constance.VIEW_UPLOAD)){
					if(!mTempBean.isFlagIsNew()){
						
						if(!mTempBean.isFlagIsUpLoadedCancel()){
							
							mFeedMessageList.set(i,mUpdateBean);
							break;	
						}
						
					}
					
				}
			}
			
			notifyDataSetChanged();
		}
		
	}
	
	public void addNewFeedAtPosition(final FeedBean mTempBean, int position) {

	}

	@Override
	public int getCount() {
		return mFeedMessageList.size();
	}

	@Override
	public Object getItem(int position) {
		return mFeedMessageList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressWarnings("deprecation")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		
		final ViewHolder holder;
		final FeedBean mFeedTempBean = mFeedMessageList.get(position);
		final String strType = mFeedTempBean.getTypeID();
		
		/** Catch View for next time used instead of every time create new one **/
		
		if (convertView == null) {

			holder = new ViewHolder();
			
			convertView = inflater.inflate(R.layout.test_list_item_layout,parent, false);

			holder.imageview_profile = (ImageView) convertView
					.findViewById(R.id.imageview_profile);

			holder.textView_header_title = (TextView) convertView
					.findViewById(R.id.textView_header_title);

			holder.textView_timeonly = (TextView) convertView
					.findViewById(R.id.textView_timeonly);

			holder.textView_Caption = (TextView) convertView
					.findViewById(R.id.textView_caption);

			holder.textView_like_counter = (TextView) convertView
					.findViewById(R.id.textView_like_counter);

			holder.textView_more_comments = (TextView) convertView
					.findViewById(R.id.textView_more_comments);

			holder.imageview_photoshared = (ImageView) convertView
					.findViewById(R.id.imageview_photoshared);
			
			holder.imageview_tran_overlay = (ImageView)convertView
					.findViewById(R.id.imageview_tran_overlay);

			holder.mProgressBar = (ProgressBar) convertView
					.findViewById(R.id.progress_horizontal);

			holder.btn_like_counter = (ImageView) convertView
					.findViewById(R.id.btn_like_counter);
			
			// ADDED NEW ITEMS IN THE CASE OF UPLOAD 
			holder.imageview_upload_cancel = (ImageView) convertView
					.findViewById(R.id.imageview_upload_cancel);

			holder.imageview_item_delete = (ImageView) convertView
					.findViewById(R.id.imageview_item_delete);

			holder.imageview_photo_overlay = (ImageView) convertView
					.findViewById(R.id.imageview_photo_overlay);
			
			holder.imageview_item_revert = (ImageView)convertView.findViewById(R.id.imageview_item_revert);
				
			convertView.setTag(holder);
			
		}else{
			/** Catch View for next time used instead of every time create new one **/
			holder = (ViewHolder) convertView.getTag();
		}
		
		
		if (mFeedTempBean != null) {
			
			/** If type is View Upload then this will execute  **/
			if (strType.equalsIgnoreCase(Constance.VIEW_UPLOAD)) {
			
			
				holder.imageview_tran_overlay.setVisibility(View.INVISIBLE);
				
				if(!mFeedTempBean.isFlagIsNew()){
					
					if(mFeedTempBean.isFlagIsUpLoadedCancel()){
						
						holder.imageview_photo_overlay.setVisibility(View.VISIBLE);
						holder.imageview_item_revert.setVisibility(View.VISIBLE);
						holder.imageview_item_delete.setVisibility(View.VISIBLE);
						
					}else{
						
						holder.imageview_tran_overlay.setVisibility(View.VISIBLE);
					}
						
				}
				
				new Handler().postDelayed(new Runnable() {
					
					@Override
					public void run() {
						holder.imageview_photoshared.setImageBitmap(UtilityHelper.decodeSampledBitmapFromResource(mFeedTempBean.getFilePath(),500,500));
					}
				}, 100);
				
				if(mFeedTempBean.isFlagIsNew()){
					
					holder.imageview_upload_cancel.setVisibility(View.VISIBLE);
					holder.imageview_photo_overlay.setVisibility(View.VISIBLE);
					holder.mProgressBar.setVisibility(View.VISIBLE);
					
					mEncoding = new ImageEncodingProcess(position,holder.mProgressBar,holder.imageview_photo_overlay,holder.imageview_upload_cancel,holder.imageview_item_revert,holder.imageview_item_delete,holder.imageview_tran_overlay);
					mEncoding.execute(mFeedTempBean.getFilePath(),mFeedTempBean.getCaptionText());
			
					
				}
				
				holder.imageview_upload_cancel.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								cancelUploadFeeds(mFeedMessageList.get(position), position);
								mEncoding.cancel(true);
								if(mShareImageTask != null){
									mShareImageTask.stopWorkerTask();	
								}
								holder.mProgressBar.setVisibility(View.INVISIBLE);
								holder.imageview_upload_cancel.setVisibility(View.INVISIBLE);
								holder.imageview_photo_overlay.setVisibility(View.VISIBLE);
								holder.imageview_item_revert.setVisibility(View.VISIBLE);
								holder.imageview_item_delete.setVisibility(View.VISIBLE);
							}
						});
				
				holder.imageview_item_delete
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								
								FlagIsClickable = false;
								Toast.makeText(mContext, " delete item ",Toast.LENGTH_SHORT).show();
								mFeedMessageList.remove(position);
								notifyDataSetChanged();
							}
						});
				
				holder.imageview_item_revert.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						holder.imageview_photoshared.setImageBitmap(null);
						
						holder.imageview_upload_cancel.setVisibility(View.VISIBLE);
						holder.imageview_photo_overlay.setVisibility(View.VISIBLE);
						holder.mProgressBar.setProgress(0);
						holder.mProgressBar.setVisibility(View.VISIBLE);
						
						holder.imageview_item_revert.setVisibility(View.INVISIBLE);
						holder.imageview_item_delete.setVisibility(View.INVISIBLE);
						
						new Handler().postDelayed(new Runnable() {
							
							@Override
							public void run() {
								
								holder.imageview_photoshared.setImageBitmap(UtilityHelper.decodeSampledBitmapFromResource(mFeedTempBean.getFilePath(),500,500));
							}
						}, 100);
						
						mEncoding = new ImageEncodingProcess(position,holder.mProgressBar,holder.imageview_photo_overlay,holder.imageview_upload_cancel,holder.imageview_item_revert,holder.imageview_item_delete,holder.imageview_tran_overlay);
						mEncoding.execute(mFeedTempBean.getFilePath(),mFeedTempBean.getCaptionText());
						
					}
				});
				// in visible the bottom trans over lay
				holder.imageview_photoshared.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						//IF feed should not new 
						if(!mFeedTempBean.isFlagIsNew()){
							
							// if not new then check is it cancel feed then it should not cancel for preview 
							if(!mFeedTempBean.isFlagIsUpLoadedCancel()){
								
								mCommentCallback.onStreamPhotoSlidingClick(position);
							}
						}
						
					}
				});
				
								

			}
			/** If type is View Downloaded then this will execute  **/
			else if (strType.equalsIgnoreCase(Constance.VIEW_DOWNLOAD)) {
				
				holder.textView_Caption.setVisibility(View.INVISIBLE);
				holder.imageview_tran_overlay.setVisibility(View.INVISIBLE);
				holder.imageview_photo_overlay.setVisibility(View.INVISIBLE);
				holder.imageview_upload_cancel.setVisibility(View.INVISIBLE);
				holder.imageview_item_revert.setVisibility(View.INVISIBLE);
				holder.imageview_item_delete.setVisibility(View.INVISIBLE);
				
				// cache image and pull to load image
				mAdapterLoader.displayImage(mFeedTempBean.getFilePath(),
						holder.imageview_photoshared, mAdapterOptions,
						new SimpleImageLoadingListener(){
							
						boolean result = false;
						int index = 0;
						@Override
						public void onLoadingStarted(String imageUri,
								View view) {
							holder.mProgressBar.setVisibility(View.VISIBLE);
							holder.mProgressBar.setProgress(index);
							new Thread(new Runnable() {

								@Override
								public void run() {

									while (!result) {
										try {

											if (index < 100) {
												holder.mProgressBar
														.setProgress(index);
												Thread.sleep(100);
												index = index + 2;
											} else {
												break;
											}

										} catch (Exception e) {
											e.printStackTrace();
										}

									}

								}
							}).start();
						}
						
						@Override
							public void onLoadingFailed(String imageUri,
									View view, FailReason failReason) {
							String message = null;
							switch (failReason) {
								case IO_ERROR:
									message = "Input/Output error";
									break;
								case OUT_OF_MEMORY:
									message = "Out Of Memory error";
									break;
								case NETWORK_DENIED:
									message = "Downloads are denied";
									break;
								case UNSUPPORTED_URI_SCHEME:
									message = "Unsupported URI scheme";
									break;
								case UNKNOWN:
									message = "Unknown error";
									break;
							}
							Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
						}
						
						@Override
							public void onLoadingComplete(String imageUri,
									View view, Bitmap loadedImage) {
							Log.d(TAG, "onLoadingComplete");
							result = true;
							holder.mProgressBar.setProgress(100);
							holder.mProgressBar.setVisibility(View.GONE);
							holder.textView_Caption.setVisibility(View.VISIBLE);
							holder.imageview_tran_overlay.setVisibility(View.VISIBLE);
						}
						
					});
				
				
						holder.imageview_photoshared
						.setOnClickListener(new OnClickListener() {
		
							@Override
							public void onClick(View v) {
								mCommentCallback.onStreamPhotoSlidingClick(position);
							}
						});
				
				}

				holder.imageview_profile
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								mCommentCallback.onProfileIconClick(position);
							}
						});
				holder.textView_header_title.setText(mFeedTempBean.getName());
				holder.textView_timeonly
						.setText(UtilityHelper
								.extractTimefromDate(mFeedTempBean
										.getCreatedDateTime()));

				holder.textView_like_counter.setText(new StringBuilder()
						.append(mFeedTempBean.getLikeCounter())
						.append(" likes"));
				holder.textView_like_counter
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								mCommentCallback
										.onStreamLikerListClick(position);
							}
						});

				holder.textView_Caption.setText(mFeedTempBean.getCaptionText());
				
				if(mFeedTempBean.getLikeCounter().equalsIgnoreCase("1")){
					holder.btn_like_counter.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.stream_photo_activity_glyph_likes_pressed));
				}else if(mFeedTempBean.getLikeCounter().equalsIgnoreCase("0")){
					holder.btn_like_counter.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.stream_photo_activity_glyph_likes));
				}
				
				holder.btn_like_counter.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						if(mFeedTempBean.getLikeCounter().equalsIgnoreCase("1")){
							holder.btn_like_counter.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.stream_photo_activity_glyph_likes));
						}else if(mFeedTempBean.getLikeCounter().equalsIgnoreCase("0")){
							holder.btn_like_counter.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.stream_photo_activity_glyph_likes_pressed));
						}
						mLikeHandler.postDelayed(new Runnable() {
				
									@Override
									public void run() {
				
										final FeedBean newFeedBean = new FeedBean();
										newFeedBean.setTypeID(mFeedTempBean.getTypeID());
										newFeedBean.setProfileID(mFeedTempBean.getProfileID());
										newFeedBean.setFeedID(mFeedTempBean.getFeedID());
										
										newFeedBean.setCaptionText(mFeedTempBean.getCaptionText());
										
										newFeedBean.setDisplayName(mFeedTempBean.getDisplayName());
																								
										newFeedBean.setName(mFeedTempBean.getName());
												
										newFeedBean.setFilePath(mFeedTempBean.getFilePath());
										
										newFeedBean.setCreatedDateTime(mFeedTempBean.getCreatedDateTime());

										int likeCounter = Integer.parseInt((mFeedTempBean.getLikeCounter().equals("") ? "0": mFeedTempBean.getLikeCounter()));
										
										if(likeCounter == 0){
											newFeedBean.setLikeCounter(String.valueOf(likeCounter + 1));	
										}else{
											newFeedBean.setLikeCounter(String.valueOf(0));	
										}
										
										mFeedMessageList.set(position,newFeedBean);
												
										notifyDataSetChanged();
									}
								}, 200);
						}
					});
					holder.textView_more_comments.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							mCommentCallback.onStreamCommentClick(position);
						}
					});
						


		}

		return convertView;
	}

	/**
	 *	Feed Header list view set from here   
	 */
	@Override
	public View getHeaderView(int position, View convertView, ViewGroup parent) {
		mHeaderUpdateCallback.resetHeaderView(position);
		HeaderViewHolder holder;
		if (convertView == null) {
			holder = new HeaderViewHolder();
			convertView = inflater.inflate(R.layout.header, parent, false);
			
			holder.mView_group_header = (LinearLayout)convertView.findViewById(R.id.view_group_header);
			holder.textView_header_timestemp = (TextView) convertView
					.findViewById(R.id.textView_timestemp);

			convertView.setTag(holder);

		} else {

			holder = (HeaderViewHolder) convertView.getTag();
		}

		if (position == 0) {
			holder.textView_header_timestemp.setVisibility(View.VISIBLE);
		} else {
			holder.textView_header_timestemp.setVisibility(View.GONE);
			holder.mView_group_header.setVisibility(View.GONE);
		}

		return convertView;
	}

	// remember that these have to be static, postion=1 should walys return the
	// same Id that is.
	@Override
	public long getHeaderId(int position) {
		// return the first character of the country as ID because this is what
		// headers are based upon
		return position;
	}

	class HeaderViewHolder {
		LinearLayout mView_group_header;
		TextView textView_header_timestemp;
	}

	/**
	 * 
	 * Feed catch view Holder 
	 *
	 */
	class ViewHolder {
		
		ImageView imageview_upload_cancel;
		ImageView imageview_item_revert;
		ImageView imageview_item_delete;
		ImageView imageview_photo_overlay;

		ImageView imageview_profile;
		TextView textView_header_title;
		TextView textView_timeonly;

		TextView textView_Caption;
		TextView textView_like_counter;
		TextView textView_more_comments;

		ImageView imageview_photoshared;
		ImageView imageview_tran_overlay;
		ProgressBar mProgressBar;
		ImageView btn_like_counter;
		Button btn_stream_comment;

		LinearLayout panel_comment_list;
	}

	/**
	 * 
	 * Before upload image encoding process 
	 *
	 */
	class ImageEncodingProcess extends AsyncTask<String, Integer, Integer> {

		String mDataBinary;
		String mCaption;
		ProgressBar mProgressBar;
		ImageView mImageview_tran_overlay;
		ImageView mImageview_photo_overlay;
		ImageView mImageview_upload_cancel;
		ImageView mImageview_retry;
		ImageView mImageview_delte;
		int mPosition;
		public ImageEncodingProcess(int vposition,ProgressBar mTempPrBar,ImageView imageview_photo_overlay,ImageView vImageview_upload_cancel,ImageView vImageview_retry,ImageView vImageview_delte,ImageView vimageview_tran_overlay) {
			mProgressBar = mTempPrBar;
			mImageview_photo_overlay = imageview_photo_overlay;
			mImageview_upload_cancel = vImageview_upload_cancel;
			mImageview_retry = vImageview_retry;
			mImageview_delte = vImageview_delte;
			mImageview_tran_overlay = vimageview_tran_overlay;
			mPosition = vposition;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mDataBinary = new String();
			mCaption = new String();
		}

		@Override
		protected Integer doInBackground(String... params) {
			int status = 0;
			int index = 0;
			
			Log.d(TAG, "[ image path]" + params[0]);
			Log.d(TAG, "[ Caption ] " + params[1]);

			mDataBinary = UtilityHelper.imageEncodeTobase64(UtilityHelper.decodeSampledBitmapFromResource(params[0],300,300));
			mCaption = params[1];
			
			while (true) {
				try {
						if(!isCancelled()){
							
							if (index < 100) {
								publishProgress(index);
								Thread.sleep(1000);
								index = index + 20;
							} else {
								
								status = 0;
								break;
							}
						}else{
							status = -1;
							break;
						}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			return status;
		}
		
		protected void onProgressUpdate(Integer... values) {
			this.mProgressBar.setProgress(values[0]);
			super.onProgressUpdate(values);
			
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (result == 0) {
				
				mShareImageTask = new NewShareImageTask(mProgressBar,mImageview_photo_overlay,mImageview_upload_cancel,mImageview_retry,mImageview_delte,mImageview_tran_overlay);
				mShareImageTask.setBinaryData(mDataBinary);
				mShareImageTask.setCaptionValue(mCaption.toString());
				mShareImageTask.setEmailAddress("test@gmail.com");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mShareImageTask.postImages();
				completeUploadFeeds(mFeedMessageList.get(mPosition), mPosition);
				
			}else{
				Toast.makeText(mContext, "Cancel Upload image",Toast.LENGTH_LONG).show();
			}
		}
	}

	/*class ShareImageTask extends AsyncTask<String, Void, Integer> {

		ProgressBar mProgressBar;
		ImageView mImageview_photo_overlay;
		ImageView mImageview_upload_cancel;
		int result = 0;
		Thread mUploadWorker;
		boolean isStartWorkerThread;
		public ShareImageTask(ProgressBar mTempProgress,ImageView imageview_photo_overlay,ImageView vImageview_upload_cancel) {
			this.mProgressBar = mTempProgress;
			mImageview_photo_overlay = imageview_photo_overlay;
			mImageview_upload_cancel = vImageview_upload_cancel;
			isStartWorkerThread = false;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressBar.setProgress(60);
		}

		@Override
		protected Integer doInBackground(final String... params) {
			
			
			
			return result;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
		}

	}*/
	
	/**
	 * To Upload Image after encoding 
	 *
	 */
	class NewShareImageTask {
		
		ProgressBar mProgressBar;
		ImageView mImageview_photo_overlay;
		ImageView mImageview_upload_cancel;
		ImageView mImageview_retry;
		ImageView mImageview_delte;
		ImageView mImageview_tran_overlay;
		
		Thread mUploadWorker;
		boolean isStartWorkerThread;
		String strBindaryValue;
		String strEmailValue;
		String strCaptionValue;
		
		NewShareImageTask(ProgressBar mTempProgress,ImageView imageview_photo_overlay,ImageView vImageview_upload_cancel,ImageView vImageview_retry,ImageView vImageview_delte,ImageView vImageview_tran_overlay) {
			this.mProgressBar = mTempProgress;
			mImageview_photo_overlay = imageview_photo_overlay;
			mImageview_upload_cancel = vImageview_upload_cancel;
			mImageview_retry = vImageview_retry;
			mImageview_delte = vImageview_delte;
			mImageview_tran_overlay = vImageview_tran_overlay; 
			isStartWorkerThread = false;
			mImageview_upload_cancel.post(new Runnable() {
				
				@Override
				public void run() {
					mImageview_upload_cancel.setVisibility(View.INVISIBLE);
				}
			});
			
		}
		
		void setBinaryData(String vBindaryValue){
			strBindaryValue = vBindaryValue;
		}
		void setCaptionValue(String vCaptionValue){
			strCaptionValue =  vCaptionValue;
		}
		void setEmailAddress(String vEmailValue){
			strEmailValue = vEmailValue;
		}
		void postImages(){
			
			mUploadWorker =	new Thread(new Runnable() {
				
				@Override
				public void run() {
					
					try {
						
						isStartWorkerThread = true;
						
						InputStream is = null;
						JSONObject mobj$Json = null;
						String json = "";

						ArrayList<JSONParams> mArrayParams;
						JSONParams mObj$Params;

						mArrayParams = new ArrayList<JSONParams>();

						mObj$Params = new JSONParams();
						mObj$Params.setStrKey(Constance.PARAN_METADATA_IMAGE);
						mObj$Params.setStrvalue(strBindaryValue);
						mArrayParams.add(mObj$Params);

						mObj$Params = new JSONParams();
						mObj$Params.setStrKey(Constance.PARAM_EMAIL);
						mObj$Params.setStrvalue(strEmailValue);

						// ADD PARAMS_LATITUDE
						mArrayParams.add(mObj$Params);

						mObj$Params = new JSONParams();
						mObj$Params.setStrKey(Constance.PARAM_CAPTION);
						mObj$Params.setStrvalue(strCaptionValue);

						// ADD PARAMS_LONGITUDE
						mArrayParams.add(mObj$Params);

						HttpParams mHttpParameters = new BasicHttpParams();
						// Set the timeout in milliseconds until a connection is
						// established.
						int timeoutConnection = 300000;
						HttpConnectionParams.setConnectionTimeout(mHttpParameters,
								timeoutConnection);
						int timeoutSocket = 300000;
						HttpConnectionParams.setSoTimeout(mHttpParameters,
								timeoutSocket);

						// defaultHttpClient
						DefaultHttpClient httpClient = new DefaultHttpClient(
								mHttpParameters);
						HttpPost httpPost = new HttpPost(Constance.POST_IMAGE_URL);
						httpPost.setHeader("Content-Type", "application/json");

						JSONObject mJSONObject = new JSONObject();
						if (mArrayParams != null) {
							for (int y = 0; y < mArrayParams.size(); y++) {
								JSONParams mobj$Params = mArrayParams.get(y);
								mJSONObject.put(mobj$Params.getStrKey(),
										mobj$Params.getStrvalue());
							}
						}

						Log.d(TAG, "[ Image ]" + mJSONObject.toString());
						StringEntity se = new StringEntity(mJSONObject.toString());
						se.setContentType("application/json");
						httpPost.setEntity(se);
						
						HttpResponse httpResponse = httpClient.execute(httpPost);
						HttpEntity httpEntity = httpResponse.getEntity();
						is = httpEntity.getContent();

						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						StringBuilder sb = new StringBuilder();
						String line = null;
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						is.close();
						json = sb.toString();

						mobj$Json = new JSONObject(json);

						String mStatus = mobj$Json.getString("status");
						String mMessage = mobj$Json.getString("statusmsg");

						Log.d(TAG, "[ STATUS ]" + mStatus);
						Log.d(TAG, "[ MESSAGE ]" + mMessage);
						
						if (mStatus.equalsIgnoreCase("ok")) {
							doPostExecution(200);
						} else {
							doPostExecution(-1);
						}
						
					}catch (Exception e) {
						e.printStackTrace();
					}
				}
				
			});
			
			if(!isStartWorkerThread){
				Log.d(TAG,"start upload worker to upload...");
				
				mUploadWorker.start();
				
			}
		}
		
		void doPostExecution(int vresult){
			
			if (vresult > 0) {

				isStartWorkerThread = false;
				mProgressBar.post(new Runnable() {
					
					@Override
					public void run() {
						
						
						mProgressBar.setProgress(100);
						
						mProgressBar.setVisibility(View.INVISIBLE);
						mImageview_tran_overlay.setVisibility(View.VISIBLE);
						mImageview_upload_cancel.setVisibility(View.INVISIBLE);
						mImageview_photo_overlay.setVisibility(View.INVISIBLE);
						mImageview_retry.setVisibility(View.INVISIBLE);
						mImageview_delte.setVisibility(View.INVISIBLE);
					}
				});
				
				muploadCallback.onUploadListener(true);
				
			} else {
				
				isStartWorkerThread = false;
			}
			
		}
		
		void stopWorkerTask(){
			
			if(mUploadWorker != null){
				mUploadWorker.interrupt();
				mUploadWorker = null;
			}
		}
		
	}
	
	/**
	 * Cancel Upload feeds for hide and visible view 
	 * @param vCancelFeedBean
	 * @param position
	 */
	public void cancelUploadFeeds(FeedBean vCancelFeedBean, int position){
		
		synchronized (vCancelFeedBean) {
			
			final FeedBean newFeedBean = vCancelFeedBean;
			newFeedBean.setFlagIsNew(false);
			newFeedBean.setFlagIsUpLoadedCancel(true);
			mFeedMessageList.set(position,newFeedBean);
			notifyDataSetChanged();
		}
	}
	
	/**
	 * After complete Upload feeds for hide and visible view 
	 * @param vCompleteFeedBean
	 * @param position
	 */
	public void completeUploadFeeds(FeedBean vCompleteFeedBean, int position){
		
		synchronized (vCompleteFeedBean) {
			
			final FeedBean newFeedBean = vCompleteFeedBean;
			newFeedBean.setTypeID(Constance.VIEW_UPLOAD);
			newFeedBean.setFlagIsNew(false);
			newFeedBean.setFlagIsUpLoadedCancel(false);
			mFeedMessageList.set(position,newFeedBean);
			notifyDataSetChanged();
		}
	
	}
	
}
